package com.itheima.httpClient;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Post方式发送请求
 */
public class Client_Post {
    public static void main(String[] args) throws  Exception {
        //获取地址
        String url1 = "http://www.itcast.cn";
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求方式
        HttpPost httpPost = new HttpPost(url1);
        //设置请求参数和请求头
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        list.add(new BasicNameValuePair("name","zhangsan"));
        list.add(new BasicNameValuePair("password","1234"));
        HttpEntity entity = new UrlEncodedFormEntity(list);//UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容

        //发送请求,获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取数据
        //获取状态码
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode ==200){
            //获取响应数据
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(html);
        }
        //关闭资源
        httpClient.close();
    }
}
